/*
 *  Copyright 2014-2015 snakerflow.com
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *     http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */
package com.base.shiro.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.base.common.utils.map.MapUtil;
import com.base.shiro.entity.OrgModel;
import com.base.shiro.entity.RoleModel;
import com.base.shiro.entity.TreeNode;
import com.base.shiro.entity.UserModel;
import com.base.shiro.web.validator.UserValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * UserController
 * @author yuqs
 * @since 0.1
 */
public class UserController extends Controller {
	
	String error =null;
	
	public void index() {
		render("userList.jsp");
	}
	public void userList(){	
//		int start=(getParaToInt("start")!=0)?getParaToInt("start"):1;
		int pageNumber=(getParaToInt("pageIndex")!=0)?getParaToInt("pageIndex")+1:1;		
		int pageSize=(getParaToInt("limit")!=0)?getParaToInt("limit"):10;		
		Page<UserModel> userList= UserModel.dao.paginate(pageNumber,pageSize,getPara("name"));
		Map<String, Object> map=MapUtil.toModel("rows", userList);
//		map.put("rows",goodsModelList.getList() );
		map.put("results",userList.getTotalRow());
		map.put("hasError", false);		
		renderJson(map);
		
	}
	
	//用户组织结构树
		public void orgUserTree() {
			List<OrgModel> orgs = OrgModel.dao.getByParent(getParaToInt("parentId"));
			List<TreeNode> trees = new ArrayList<TreeNode>();
			TreeNode node = null;
			for(OrgModel org : orgs) {
				node = new TreeNode();
				node.setId(org.getInt("id"));
				Integer parentOrg = org.getInt("parent_org");
				node.setpId(parentOrg == null ? OrgModel.ROOT_ORG_ID : parentOrg);
				node.setName(org.getStr("name"));
				if(parentOrg == null) {
					node.setOpen(true);
				}
				trees.add(node);
			}
			
			List<UserModel> users = UserModel.dao.getByOrg(getParaToInt("parentId"));
			for(UserModel user : users) {
				node = new TreeNode();
				node.setId(user.getInt("id"));
				Integer parentOrg = user.getInt("org");
				node.setpId(parentOrg == null ? OrgModel.ROOT_ORG_ID : parentOrg);
				node.setName(user.getStr("fullname"));
				trees.add(node);
			}
			renderJson(trees);
		}
	public void add() {
		setAttr("roles", RoleModel.dao.getAllRoles());
		render("userAdd.jsp");
	}
	
	public void edit() {
		setAttr("user", UserModel.dao.get(getParaToInt()));
		List<RoleModel> roles = RoleModel.dao.getAllRoles();
		List<RoleModel> rs = UserModel.dao.getRoles(getParaToInt());
		for(RoleModel role : roles) {
			for(RoleModel r : rs) {
				if(role.getInt("id").intValue() == r.getInt("id").intValue())
				{
					role.put("selected", 1);
				}
				if(role.get("selected") == null)
				{
					role.put("selected", 0);
				}
			}
		}
		setAttr("roles", roles);
		render("userEdit.jsp");
	}
	
	public void view() {
		setAttr("user", UserModel.dao.get(getParaToInt()));
		setAttr("roles", UserModel.dao.getRoles(getParaToInt()));
		render("userView.jsp");
	}
	
	@Before({UserValidator.class, Tx.class})
	public void save() {
		Integer[] orderIndexs = getParaValuesToInt("orderIndexs");
		UserModel model = getModel(UserModel.class);
		if (StringUtils.isNotBlank(model.getStr("plainPassword"))) {
			model.entryptPassword(model);
		}
		model.save();
		if(orderIndexs != null) {
			for(Integer orderIndex : orderIndexs) {
				UserModel.dao.insertCascade(model.getInt("id"), orderIndex);
			}
		}
		redirect("/ms/shiro/user");
	}
	
	@Before({UserValidator.class, Tx.class})
	public void update() {
		Integer[] orderIndexs = getParaValuesToInt("orderIndexs");
		UserModel model = getModel(UserModel.class);
		if (StringUtils.isNotBlank(model.getStr("plainPassword"))) {
			model.entryptPassword(model);
		}
		model.update();
		UserModel.dao.deleteCascade(model.getInt("id"));
		if(orderIndexs != null) {
			for(Integer orderIndex : orderIndexs) {
				UserModel.dao.insertCascade(model.getInt("id"), orderIndex);
			}
		}
		redirect("/ms/shiro/user");
	}
	
	@Before(Tx.class)
	public void delete() {
		UserModel.dao.deleteCascade(getParaToInt());
		UserModel.dao.deleteById(getParaToInt());
		redirect("/ms/shiro/user");
	}		
}


